<template>
  <div v-loading="loading">
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button
              type="primary"
              @click="handleUpdate"
              v-hasPermi="['financial:invoiceManage:edit']"
              >编辑</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleDelete"
              v-hasPermi="['financial:invoiceManage:dele']"
              >删除</el-button
            >
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container invoice-form px-80">
      <el-descriptions title="用户信息" :column="1" border>
        <template #title>
          <TitleName
            title="基本信息"
            icon="i-carbon-bookmark-filled"
          ></TitleName>
        </template>
        <el-descriptions-item
          label="开票日期"
          label-align="right"
          label-class-name="w-40"
          class-name="break-all"
          >{{ formData.invoiceDate }}</el-descriptions-item
        >
        <el-descriptions-item
          label="开票金额"
          label-align="right"
          label-class-name="w-40"
          class-name="break-all"
          >¥{{ formData.price }}</el-descriptions-item
        >
        <el-descriptions-item
          label="开票方"
          label-align="right"
          class-name="break-all"
          >{{ formData.customerName }}</el-descriptions-item
        >
        <el-descriptions-item
          label="关联订单"
          label-align="right"
          class-name="break-all"
          >{{ formData.orderTitle }}</el-descriptions-item
        >
        <el-descriptions-item
          label="票据类型"
          label-align="right"
          class-name="break-all"
        >
          <dict-drop
            :options="invoice_manage_type"
            :value="formData.type"
            :isDrop="false"
        /></el-descriptions-item>
        <el-descriptions-item
          label="票据内容"
          label-align="right"
          class-name="break-all"
        >
          {{ formData.content }}
        </el-descriptions-item>
        <el-descriptions-item
          label="发票号码"
          label-align="right"
          class-name="break-all"
          >{{ formData.number }}</el-descriptions-item
        >
        <el-descriptions-item
          label="发票经手人员"
          label-align="right"
          class-name="break-all"
          >{{ formData.handleUserName }}</el-descriptions-item
        >
        <el-descriptions-item
          label="订单归属人员"
          label-align="right"
          class-name="break-all"
          >{{ formData.orderBelongUserName }}</el-descriptions-item
        >
        <el-descriptions-item
          label="备注信息"
          label-align="right"
          class-name="break-all"
          >{{ formData.remark }}</el-descriptions-item
        >
        <el-descriptions-item
          v-if="formData.pdfUrl"
          label=""
          label-align="right"
          class-name="break-all"
        >
          <el-button @click="viewFile(formData.pdfUrl)">发票预览</el-button>
          <el-button @click="downLoadFile(formData.pdfUrl)">发票下载</el-button>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="pt-5" title="系统信息" :column="1" border>
        <template #title>
          <TitleName
            title="系统信息"
            icon="i-carbon-bookmark-filled"
          ></TitleName>
        </template>
        <el-descriptions-item
          label="录入人员"
          label-align="right"
          label-class-name="w-40"
          >{{ formData.createByName }}</el-descriptions-item
        >
        <el-descriptions-item
          label="创建时间"
          label-align="right"
          label-class-name="w-40"
          >{{ formData.createTime }}</el-descriptions-item
        >
        <el-descriptions-item label="更新时间" label-align="right">{{
          formData.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    ></SelectCustomer>
  </div>
</template>
<script setup name="InvoiceDetails">
import { reactive, toRefs, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import {
  setInvoice,
  getInvoiceDetail,
  delInvoice
} from '@/api/invoiceManage/invoice'
import { listSalesOrderSelect } from '@/api/indentManage/indent'
import {
  loadingSelect, //远程检索loading
  indentOptionLimitEnt, // 订单数据
  queryIndentLimitEnt // 检索订单数据
} from '@/hooks/dict/order'
import useTagsViewStore from '@/store/modules/tagsView'
import { isMoneyNot } from '@/utils/validate'
import useUserStore from '@/store/modules/user'
import { getTreeNodeByParam, getPricipalId, viewFile } from '@/utils/commo'
import { getWorkDay, getLatestMsg, addManage } from '@/api/system/notice'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const userOption = ref({}) //通知人员下拉
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})

const { invoice_manage_type, pay_type, settle_type } = proxy.useDict(
  'invoice_manage_type', //票据类型
  'pay_type', //付款方式
  'settle_type' //结算方式
)

const props = defineProps({
  invoiceData: {
    type: Object,
    require: false,
    default: null
  },
  invoiceId: {
    type: Object,
    require: false,
    default: null
  }
})
const data = reactive({
  formData: {
    customerType: 'customer' //客户类型
  },
  formRules: {
    invoiceDate: [
      {
        required: true,
        message: '请选择开票日期',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入开票金额',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择开票方',
        trigger: 'change'
      }
    ],
    orderId: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ],
    type: [
      {
        required: true,
        message: '请选择发票类型',
        trigger: 'change'
      }
    ],
    content: [
      {
        required: true,
        message: '请选择开票内容',
        trigger: 'blur'
      }
    ],
    number: [
      {
        required: true,
        message: '请选择发票号',
        trigger: 'blur'
      }
    ],
    handleUserId: [
      {
        required: true,
        message: '请选择经手人员',
        trigger: 'change'
      }
    ]
  },

  dialogParam: {} /* 人员弹窗框参数 */,
  customerOption: {}, //客户选择下拉
  dialogParamA: {} /* 客户弹窗框参数 */,
  loading: false
})
const {
  formData,
  formRules,
  dialogParam,
  customerOption,
  dialogParamA,
  loading
} = toRefs(data)
// watch(
//   () => data.formData.productInfoList,
//   (newVal, oldValue) => {
//     let price = 0
//     formData.value.productInfoList.forEach(e => {
//       if (e.id) {
//         price = e.price * e.num + price
//       }
//     })
//     formData.value.price = price
//   },
//   { deep: true }
// )
watchEffect(() => {
  if (route.query.invoiceId && route.name == type.name) {
    console.log('instance.type.name-->', type.name)
    getFormData(route.query.invoiceId)
  } else if (route.query.invoiceData && route.name == type.name) {
    let invoiceData = JSON.parse(route.query.invoiceData)
    formData.value.customerId = invoiceData.customerId
    formData.value.customerName = invoiceData.customerName
    formData.value.orderId = invoiceData.orderId
    // formData.value.invoicePlanId = invoiceData.period
    customerOption.value['customerId'] = [
      {
        id: invoiceData.customerId,
        label: invoiceData.customerName
      }
    ]
    indentOptionLimitEnt.value = [
      {
        orderId: invoiceData.orderId,
        orderTitle: invoiceData.orderTitle
      }
    ]
  }
  if (props.invoiceId) {
    console.log('props.invoiceId==>', props.invoiceId)
    getFormData(props.invoiceId)
  }
})
/** 获取详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  getInvoiceDetail(id).then(async res => {
    let resData = {}
    resData = res.data
    customerOption.value['customerId'] = [
      {
        label: resData.customerName, //? resData.customerName: resData.customerId,
        id: resData.customerId //? resData.customerId : resData.customerName
      }
    ]
    indentOptionLimitEnt.value = [
      {
        orderTitle: resData.orderTitle, //? resData.customerName: resData.customerId,
        orderId: resData.orderId //? resData.customerId : resData.customerName
      }
    ]
    formData.value = resData
    // 经手人员
    await getDefaultUserInfo(
      formData.value.handleUserId,
      'handleUserId',
      'formhandleUserId'
    )
  })
}

// 初始化
function init() {}
// 编辑
function handleUpdate() {
  goTo('/financial/editInvoice', { invoiceId: formData.value.id })
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 删除
function handleDelete(row) {
  proxy.$modal
    .confirm('是否删除该票据')
    .then(function () {
      let data = {
        ids: [formData.value.id],
        type: 'invoice'
      }
      return delInvoice(data)
    })
    .then(() => {
      proxy.$modal.msgSuccess('删除成功')
      handleReturn()
    })
    .catch(() => {})
}

function handleReset() {
  console.log('清除')
  formData.value = {}
  proxy.resetForm('sortRef')
  //   proxy.$refs.form.resetForm()
}

/* 人员选择
 * @param {string}
 */
function selectUserFn(keyName) {
  dialogParam.value.type = keyName
  dialogParam.value.title = '经手人员'
  dialogParam.value.isDialog = true
  dialogParam.value.multiple = false
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.defaultCheckedKeys = [formData.value[keyName]]
  dialogParam.value.dataType = 'person'
}
// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'formhandleUserId':
      userOption.value.formhandleUserId = val.selectData
      formData.value.handleUserId = val.defaultCheckedKeys.toString()
      break
  }
}
// 人员id转uuid
async function getDefaultUserInfo(val, fieldName, selectArr) {
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  } else {
    return
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData()
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(deptUserData, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

// 改变客户名称后
const changeCustomer = val => {
  // formData.value.customerName = obj[0].customerName
  formData.value.orderId = null
  queryIndentLimitEnt(undefined, val)
}
/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = formData.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
  }
}
// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      if (formData.value.customerId !== val.defaultCheckedKeys.toString()) {
        changeCustomer(val.defaultCheckedKeys.toString())
      }
      formData.value.customerType = val.tabVal
      formData.value.customerName = val.labelData.toString()
      formData.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

// 下载发票
const downLoadFile = url => {
  window.open(url)
}

// 订单赋值
function changeIndent(row) {
  console.log('row==>', row)
  let newData = JSON.parse(JSON.stringify(indentOptionLimitEnt.value))
  let obj = newData.filter(item => {
    return item.orderId == row
  })
  formData.value.orderTitle = obj[0].orderTitle
}
// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.invoice-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}
</style>
